<template>
  <div>
    <el-tag closable type="primary" effect="dark"
      style="border-radius: 0px; padding: 12px 10px; cursor: pointer; margin: 3px 0 3px 20px;">
      <span style="background-color: white; border-radius: 50%; width: 8px; height: 8px; display: inline-block;"></span>
      <span style="padding-left: 5px;">在线用户</span>
    </el-tag>
  </div>
  <!-- ============================= -->
  <hr>

  <el-button type="primary" plain icon="Plus" style="padding: 0 15px; height: 28px; margin: 5px 0 0 20px;" @click="onAdd">
    <span style="font-size: 13px; font-weight: normal; padding-right: 0px;">新增</span>
  </el-button>

  <el-button type="danger" plain icon="Delete" style="padding: 0 15px; height: 28px; margin: 5px 0 0 20px;" @click="onDeletes">
    <span style="font-size: 13px; font-weight: normal; padding-right: 0px;">删除</span>
  </el-button>

  <el-table :data="tableData" style="width: 100%"
    @selection-change="handleSelectionChange">

    <el-table-column type="selection" width="55" />
    <el-table-column fixed prop="id" label="编号" width="150" />
    <el-table-column prop="userName" label="用户名" width="150" />
    <el-table-column prop="password" label="密码" width="120" />
    <el-table-column prop="nickName" label="角色昵称" width="150" />
    <el-table-column prop="name" label="角色英文名" width="150" />
    <el-table-column prop="sex" label="性别" width="120" />
    <el-table-column prop="phone" label="电话" width="120" />
    <el-table-column prop="imageUrl" label="图片" width="120">
      <template #default="scope">
        <el-image v-if="scope.row.imageUrl" style="width: 100px; height: 100px" :src="url+ scope.row.imageUrl "
          :fit="fit" />
        <!-- {{url + scope.row.imageUrl }} -->
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" min-width="120">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="onEdit(scope.row)">修改</el-button>
        <el-button link type="primary" @click="onDel(scope.row.id)" size="small">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <el-pagination
  v-model:current-page="queryInfo.pageNum"
  v-model:page-size="queryInfo.pageSize"
  :page-sizes="[2, 3, 4, 5, 6]"
  layout="total, sizes, prev, pager, next, jumper"
  :total="total"
  @size-change="handleSizeChange"
  @current-change="handleCurrentChange"
  />

<!-- 对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="500"
    :before-close="handleClose"
  >
  <el-form :model="user" label-width="auto" style="max-width: 600px">
    <el-form-item label="用户名">
      <el-input v-model="user.userName" />
    </el-form-item>
    <el-form-item label="密码">
      <el-input v-model="user.password" />
    </el-form-item>
    <el-form-item label="角色昵称">
      <el-input v-model="user.nickName" />
    </el-form-item>
    <el-form-item label="角色英文名">
      <el-input v-model="user.name" />
    </el-form-item>
    <el-form-item label="性别">
      <el-input v-model="user.sex" />
    </el-form-item>
    <el-form-item label="电话">
      <el-input v-model="user.phone" />
    </el-form-item>
    <el-form-item label="图片">

      <!-- <el-input v-model="user.imageUrl" /> -->
      <el-upload
        class="avatar-uploader"
        action="http://localhost:8080/file/upload"
        v-model:file-list="fileList"
        :show-file-list="true"
        list-type="picture-card"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>

    </el-form-item>
  </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="addOrUpdate">
          {{title}}
        </el-button>
        <el-button @click="close">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios';

const multipleSelection = ref([]);

const handleSelectionChange = (val) => {
  multipleSelection.value = [];
  val.forEach(element => {
    multipleSelection.value.push(element.id);
  });
}

//批量删除
const onDeletes = () => {

  if(multipleSelection.value.length == 0){
    ElMessage.warning('请选择要删除的用户'); 

  } else{

    ElMessageBox.confirm(
    '您确定要删除这些用户吗？',
    '系统提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
      .then(() => {
        // let arr = ref([27,29,30]);
        axios.delete('users/deletes', {
          params: {
            list: multipleSelection.value
          },
          paramsSerializer: params => {
            return Object.keys(params)
              .map(key => `${key}=${params[key].join(',')}`)
              .join('&');
          },
        })
          .then(res => {
            if (res.data.code == 1) {
              ElMessage({
                type: 'success',
                message: 'Delete completed',
              })
              getList();
            }
          })

      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: 'Delete canceled',
        })
      })

  }

}

const url = 'http://localhost:8080/file/downLoad?fileName=';
const tableData = ref([]);

onMounted(() => {
   getList(); 
})

const queryInfo = ref({
    pageNum: 1,
    pageSize: 3,
    userName: '',
    password: ''
})

const total = ref(0);

const getList = ()=>{
    axios.get('users/findByPage', {
        params: queryInfo.value
    })
    .then(res=>{
      let result = res.data;
      // console.log(res);
      if(result.code == 1){
        tableData.value = result.data.list;
        total.value = result.data.total;
      }
    })
}

//分页
const handleSizeChange = (val) => {
  queryInfo.value.pageSize = val;
  queryInfo.value.pageNum = 1;
  getList();
}
const handleCurrentChange = (val) => {
  queryInfo.value.pageNum = val;
  getList();
}
const title = ref('');
const dialogVisible = ref(false);
const user = ref({
    userName: '1',
    password: '2',
    nickName: '3',
    name: '4',
    sex: '5',
    phone: '6', 
    imageUrl: '7'
})

//确定修改或添加
const addOrUpdate = ()=>{
    if(title.value == '添加'){
        axios.post('users/add', user.value)
         .then(res => {
            getList();
            dialogVisible.value = false;
            ElMessage({
              type:'success',
              message: 'Add completed',
            })
          }) 
    }else{
        axios.put('users/update', user.value)
        .then(res => {
            getList();
            dialogVisible.value = false;
            ElMessage({
              type:'success',
              message: 'Update completed',
            })
          })
    }  
}

const fileList = ref([]);

//新增
const onAdd = ()=>{
    dialogVisible.value = true;
    title.value = '添加';
    user.value = {
        userName: '',
        password: '',
        nickName: '',
        name: '',
        sex: '',
        phone: '',
        imageUrl: '' 
    }
    fileList.value = [];

}
//修改
const onEdit = (row)=>{
    dialogVisible.value = true;
    title.value = '修改';
    user.value = row;
    fileList.value = [
      {
        url: url + user.value.imageUrl,
        name: user.value.imageUrl,
      }
    ];
}
//取消
const close = ()=>{
    dialogVisible.value = false;
    getList();
    fileList.value = [];
}

//上传成功的方法
const handleAvatarSuccess = (res, file) => {
  // console.log(res);
  user.value.imageUrl = res.data;
}

const onDel = (id)=>{
    ElMessageBox.confirm(
    '是否确认强退名称为'+'"'+name+'"'+'的用户?',
    '系统提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
      .then(() => {
        axios.delete('users/' + id)
          .then(res => {
            getList();
            ElMessage({
              type: 'success',
              message: 'Delete completed',
            })
          })

      })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
}
</script>

<style scoped>
*{padding: 0; margin: 0;}
.ml200{margin-left: 200px;}

.container{padding: 20px;}
nav{color: rgb(80, 80, 80);}
nav b{padding: 0 10px; font-size: 14px;}

table{border-collapse: collapse;}
table tr{border-bottom: 1px solid black; text-align: center; border-color: rgb(218, 218, 218)}
table tr:hover{background-color: rgb(235, 235, 235);}
table tr th{padding: 15px 0; width: 126px; color: #555E71; font-size: 13px;}
table tr th:first-child{width: 50px;}
table tr th:nth-child(9){width: 180px;}

tr td{color: #828487; font-size: 14px; padding: 15px 0;}
tr td div{display: inline-block; cursor: pointer;}
tr td span{font-size: 12px; color: #3EA2FF;}

footer{position: relative; height: 32px; margin-top: 20px;}
.f-container{display: inline-block; position: absolute; right: 0px;}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>